package net.sf.jOpinionPoll.security;

import java.util.Iterator;
import org.apache.log4j.Logger;

import net.sf.jOpinionPoll.entity.Papel;
import net.sf.jOpinionPoll.entity.Usuario;
import net.sf.jOpinionPoll.facade.UsuarioFacade;

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;

public class UserDetailsServiceImpl implements UserDetailsService {

	private static final Logger m_Logger = Logger.getLogger(UserDetailsServiceImpl.class);
	private UsuarioFacade m_UsuarioFacade;
    
	public void setUsuarioFacade(UsuarioFacade usuarioFacade) {
		m_UsuarioFacade = usuarioFacade;
	}

	@Override
	public UserDetails loadUserByUsername(String login)
			throws UsernameNotFoundException, DataAccessException 
	{
        int i;
		Usuario u;
        Iterator<Papel> ir;
        GrantedAuthority[] arrayAuths;
        
		m_Logger.info("Verificando acesso para usuario " + login);
        
		u = m_UsuarioFacade.findFetchByPk(login.toLowerCase());
			
		if (u == null) {
			throw new UsernameNotFoundException("Usuario " + login + " nao encontrado!");
		}

        i = u.getPapeis().size();
        arrayAuths = new GrantedAuthority[i];
        ir = u.getPapeis().iterator();
        
        while(ir.hasNext()) {
        	arrayAuths[--i] = new GrantedAuthorityImpl(ir.next().getTipoDePapel());
		}
        
		return new User(login,
                u.getSenha(), u.getHabilitado(),
                true, true, true,
                arrayAuths);
	}
}